﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using InventoryManagement;
using MII_FIF.Common;

namespace MII_FIF.Layouts.MII_FIF
{
    public partial class FormVM : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Generic.IsUserInGroup(Configuration.DeviceManagementGroupName))
            {
                ((Label)Header.FindControl("lblHeader")).Text = "Device Management - Form VM";
                if (!IsPostBack)
                {
                    ViewState["EditMode"] = false;
                    if (Request.QueryString["ID"] != null)
                    {
                        ViewState["ID"] = Request.QueryString["ID"].ToString();
                        ViewState["EditMode"] = true;
                    }
                    Initialize();
                }
            }
            else
            {
                Response.Redirect(Generic.GenLink("/"));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DeviceManagement/ViewVM.aspx"));
        }
        

        void Initialize()
        {
            #region BindDDL
            System_Brand brand = new System_Brand();
            brand.IsDeleted = false;
            DataTable brandColl = brand.SelectByParam();
            Generic.BindDDL(ddlSystemBrand, brandColl, System_Brand_Fields.Title.ToString(), System_Brand_Fields.ID.ToString());            
            System_Type type = new System_Type();
            type.IsDeleted = false;
            DataTable typeColl = type.SelectByParam();
            Generic.BindDDL(ddlSystemType, typeColl, System_Type_Fields.Title.ToString(), System_Type_Fields.ID.ToString());            
            Location location = new Location();
            location.IsDeleted = false;
            DataTable dtLocation = location.SelectByParam();
            Generic.BindDDL(ddlLocation, dtLocation, Location_Fields.Lokasi.ToString(), Location_Fields.ID.ToString());
            Rack_Number rackNumber = new Rack_Number();
            rackNumber.IsDeleted = false;
            DataTable dtRackNumber = rackNumber.SelectByParam();
            Generic.BindDDL(ddlRackNumber, dtRackNumber, Rack_Number_Fields.Title.ToString(), Rack_Number_Fields.ID.ToString());
            Operating_System os = new Operating_System();
            os.IsDeleted = false;
            DataTable dtOperatingSystem = os.SelectByParam();
            Generic.BindDDL(ddlOperatingSystem, dtOperatingSystem, Operating_System_Fields.Title.ToString(), Operating_System_Fields.ID.ToString());
            #endregion

            if (Request.QueryString["ID"] != null)
            {
                Guid ID = Guid.Empty;
                if (Guid.TryParse(Request.QueryString["ID"], out ID))
                {
                    Inventory_VM invVM = new Inventory_VM();
                    invVM.ID = ID;
                    invVM.Select();
                    lblInventoryBy.Text = invVM.InventoryBy;
                    ddlRackNumber.SelectedValue = invVM.ID_RackNumber.ToString();
                    ddlRackNumber_SelectedIndexChanged(this, EventArgs.Empty);
                    ddlPhysicalServer.SelectedValue = invVM.ID_LabelName.ToString();
                    txtDate.Text = invVM.Date.HasValue ? invVM.Date.Value.ToString("dd-MM-yyyy") : null;
                    ddlLocation.SelectedValue = invVM.ID_DataCabang.ToString();
                    rblSystemClass.Items.IndexOf(rblSystemClass.Items.FindByValue(invVM.SystemClass));
                    ddlStartFrom.SelectedValue = invVM.StartFrom;
                    ddlSystemBrand.SelectedValue = invVM.ID_SysBrand.ToString();
                    ddlSystemType.SelectedValue = invVM.ID_SysType.ToString();
                    txtSystemDetail.Text = invVM.SystemDetail;
                    txtHostName.Text = invVM.Host_Name;
                    txtIPVM.Text = invVM.Host_IP;                   
                    ddlOperatingSystem.SelectedValue = invVM.ID_OperatingSystem.ToString();
                    txtApplication.Text = invVM.Guest_Application;
                    txtGuestProcessorUnit.Text = invVM.Guest_Processor.ToString();
                    txtGuestMemory.Text = invVM.Guest_Memory.ToString();
                    txtGuestDiskUnit.Text = invVM.Guest_Disk.ToString();
                    txtGuestDiskProvisioned.Text = invVM.Guest_DiskCapacity.ToString();
                    txtNotes.Text = invVM.Guest_Notes;
                    ViewState["Link"] = invVM.URLAttachment;

                    string filename = Generic.GetFileNameFromUrl(invVM.URLAttachment);
                    lblFileName.Text = filename;
                    btnDownload.Visible = !string.IsNullOrEmpty(filename);
                    lblFileName.Visible = !string.IsNullOrEmpty(filename);
                    FUAttachment.Visible = false;
                }
            }
            else
            {
                lblInventoryBy.Text = SPContext.Current.Web.CurrentUser.Name;
                txtDate.Text = DateTime.Now.ToString("dd-MM-yyyy");
                btnDownload.Visible = false;
                lblFileName.Visible = false;
                FUAttachment.Visible = true;
            }
        }

        bool validasi()
        {
            bool check = true;
            lblerror.Text = string.Empty;
            if (!(bool)ViewState["EditMode"])
            {
                /*if (!FUAttachment.HasFile)
                {
                    lblerror.Text += "Please upload attachment. <br />"; check = false;
                }
                else */
                if (Generic.checkUploadedFileName(FUAttachment.FileName))
                {
                    lblerror.Text += "Uploaded file name cannot contains # % & * : < > ? /  { | } <br />"; check = false;
                }
            }            
            return check;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (validasi())
            {
                Inventory_VM invVM = new Inventory_VM();
                invVM.InventoryBy = lblInventoryBy.Text;
                invVM.ID_LabelName = StringUtil.ToGuid(ddlPhysicalServer.SelectedValue);
                invVM.ID_RackNumber = StringUtil.ToGuid(ddlRackNumber.SelectedValue);
                invVM.Date = DateTime.ParseExact(txtDate.Text, "dd-MM-yyyy", System.Globalization.CultureInfo.CurrentCulture);
                invVM.ID_DataCabang = StringUtil.ToGuid(ddlLocation.SelectedValue);
                invVM.SystemClass = rblSystemClass.SelectedValue;
                invVM.StartFrom = ddlStartFrom.SelectedValue;
                invVM.ID_SysBrand = StringUtil.ToGuid(ddlSystemBrand.SelectedValue);
                invVM.ID_SysType = StringUtil.ToGuid(ddlSystemType.SelectedValue);
                invVM.SystemDetail = txtSystemDetail.Text;
                invVM.Host_Name = txtHostName.Text;
                invVM.Host_IP = txtIPVM.Text;
                invVM.ID_OperatingSystem = StringUtil.ToGuid(ddlOperatingSystem.SelectedValue);
                invVM.Guest_Application = txtApplication.Text;
                invVM.Guest_Processor = StringUtil.ToInt32(txtGuestProcessorUnit.Text);
                invVM.Guest_Memory = StringUtil.ToInt32(txtGuestMemory.Text);
                invVM.Guest_Disk = StringUtil.ToInt32(txtGuestDiskUnit.Text);
                invVM.Guest_DiskCapacity = StringUtil.ToInt32(txtGuestDiskProvisioned.Text);
                invVM.Guest_Notes = txtNotes.Text;
                invVM.InventoryDate = DateTime.Now;
                invVM.IsDeleted = false;

                if (Request.QueryString["ID"] != null)
                {
                    Guid ID = Guid.Empty;
                    if (Guid.TryParse(Request.QueryString["ID"], out ID))
                    {
                        invVM.URLAttachment = ViewState["Link"] as string;
                        invVM.ID = ID;
                        invVM.Update();
                    }
                }
                else
                {
                    invVM.URLAttachment = Generic.UploadFile(FUAttachment);
                    invVM.ID = Guid.NewGuid();
                    invVM.Insert();
                }
                Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DeviceManagement/ViewVM.aspx"));
            }
            else
            {
                ViewState["valid"] = false;
            }
        }

        protected void ddlRackNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdatePhysicalServer();
        }

        void UpdatePhysicalServer()
        {
            if (!ddlRackNumber.SelectedValue.Equals("-1"))
            {
                Inventory_Physical physical = new Inventory_Physical();
                physical.ID_RackNumber = Guid.Parse(ddlRackNumber.SelectedValue);
                physical.IsDeleted = false;
                DataTable dtPhy = physical.SelectByParam();
                Generic.BindDDL(ddlPhysicalServer, dtPhy, Inventory_Physical_Fields.LabelName.ToString(), Inventory_Physical_Fields.ID.ToString());
                ddlRackNumber.Focus();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {

            string script =
                           "function download() {" +
                           "var link ='" + ViewState["Link"] + "';" +
                           "var retvalue = window.open('" + Generic.GenLink("/_layouts/MII_FIF/Download.aspx") + "?links=' + link"
                         + ", '', 'width=1000,height=1000');}";

            Page.ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "opendownload", script, true);
        }

        protected void ddlPhysicalServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!ddlPhysicalServer.SelectedValue.Equals("-1"))
            {
                Inventory_Physical physical = new Inventory_Physical();
                physical.ID = Guid.Parse(ddlPhysicalServer.SelectedValue);
                physical.Select();
                ddlLocation.SelectedValue = physical.ID_DataCabang.ToString();
                rblSystemClass.SelectedValue = physical.SystemClass;
                ddlStartFrom.SelectedValue = physical.StartFrom;
                ddlSystemBrand.SelectedValue = physical.ID_SysBrand.ToString();
                ddlSystemType.SelectedValue = physical.ID_SysType.ToString();
                txtSystemDetail.Text = physical.SystemDetail;
            }
        }

        protected void ddlSystemBrand_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateSystemType();
        }

        void UpdateSystemType()
        {
            if (!ddlSystemBrand.SelectedValue.Equals("-1"))
            {
                System_Type type = new System_Type();
                type.ID_SystemBrand = StringUtil.ToGuid(ddlSystemBrand.SelectedValue);
                DataTable datatable = type.SelectByParam();
                Generic.BindDDL(ddlSystemType, datatable, System_Type_Fields.Title.ToString(), System_Type_Fields.ID.ToString());
                ddlSystemBrand.Focus();
            }
        }
    }
}
